/*
 *所有关于SysDepartment类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*SysDepartmentService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Collections.Generic;
using System.Linq;
using TradeDataAPI.Core.Extensions;
using TradeDataAPI.Core.ManageUser;
using TradeDataAPI.Core.UserManager;
using TradeDataAPI.Core.Utilities;
using TradeDataAPI.Entity.DomainModels;
using TradeDataAPI.System.IRepositories;
using System.Threading.Tasks;
using TradeDataAPI.Core.CacheManager;
using Newtonsoft.Json;
using TradeDataAPI.Core.EFDbContext;
using Microsoft.EntityFrameworkCore;
using System;
using TradeDataAPI.Core.Common;

namespace TradeDataAPI.System.Services
{
    public partial class SysDepartmentService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ISysDepartmentRepository _repository;//访问数据库
        private readonly ICacheService _cacheService;

        [ActivatorUtilitiesConstructor]
        public SysDepartmentService(
            ICacheService cacheService,
            ISysDepartmentRepository dbRepository,
            IHttpContextAccessor httpContextAccessor
            )
        : base(dbRepository)
        {
            _cacheService = cacheService;
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
        }


 



        /// <summary>
        /// 根据id获取部门信息- 缓存30秒
        /// </summary>
        /// <param name="DepartmentId"></param>
        /// <returns></returns>
        public async Task<SysDepartment> GetDeptByDepartmentId(string DepartmentId)
        {
            string key = $"SysDepartment_GetDeptByDepartmentId_{DepartmentId}";
            if (_cacheService.Exists(key))
            {
                var json = _cacheService.Get(key);
                return JsonConvert.DeserializeObject<SysDepartment>(json);
            }
            if (string.IsNullOrWhiteSpace(DepartmentId))
            {
                return null;
            }
            Guid.TryParse(DepartmentId, out Guid deptId);
            var data= await _repository.FindFirstAsync(x => x.DepartmentId == deptId);
            if (data != null)
            {
                _cacheService.Add(key, JsonConvert.SerializeObject(data),30);
            }   
            return data;
        }
 
 


        /// <summary>
        /// 获取全部部门id
        /// </summary>
        /// <returns></returns>
        public async Task<List<SysDepartment>> GetAllDeptIds(int Factory)
        {

            _ = _httpContextAccessor;
            string key= $"SysDepartment_GetAllDeptIds_{Factory}";
            if (_cacheService.Exists(key))
            {
                var json=_cacheService.Get(key);
                return JsonConvert.DeserializeObject<List<SysDepartment>>(json);
            }

            //var data = await repository.FindAsync(x => x.Factory == Factory);
            //if (data.Count > 0)
            //{
            //    _cacheService.Add(key, JsonConvert.SerializeObject(data), 5 * 60);
            //}
            //return data;
            using (var context = new VOLContext())
            {
                var data = await context.Set<SysDepartment>().Where(x => x.Factory == Factory).ToListAsync();
                if (data.Count > 0)
                {
                    _cacheService.Add(key, JsonConvert.SerializeObject(data), 5 * 60);
                }
                return data;
            }


        }

        public override PageGridData<SysDepartment> GetPageData(PageDataOptions options)
        {
            FilterData();
            return base.GetPageData(options);
        }

        private void FilterData()
        {
            //限制 只能看自己部门及下级组织的数据
            QueryRelativeExpression = (IQueryable<SysDepartment> queryable) =>
            {
                if (UserContext.Current.IsSuperAdmin)
                {
                    return queryable;
                }
                var deptIds = UserContext.Current.GetAllChildrenDeptIds();
                return queryable.Where(x => deptIds.Contains(x.DepartmentId));
            };
        }
        public override WebResponseContent Export(PageDataOptions pageData)
        {
            FilterData();
            return base.Export(pageData);
        }

        WebResponseContent webResponse = new WebResponseContent();
        public override WebResponseContent Add(SaveModel saveDataModel)
        {
            saveDataModel.MainData["status"] = 0;
            AddOnExecuting = (SysDepartment dept, object list) =>
            {
                return webResponse.OK();
            };
            return base.Add(saveDataModel).Reload();
        }
        public override WebResponseContent Update(SaveModel saveModel)
        {
            saveModel.MainData["status"] = 1;
            UpdateOnExecuting = (SysDepartment dept, object addList, object updateList, List<object> delKeys) =>
            {
                if (_repository.Exists(x => x.DepartmentId == dept.ParentId && x.DepartmentId == dept.DepartmentId))
                {
                    return webResponse.Error("上级组织不能选择自己");
                }
                if (_repository.Exists(x => x.ParentId == dept.DepartmentId) && _repository.Exists(x => x.DepartmentId == dept.ParentId))
                {
                    return webResponse.Error("不能选择此上级组织");
                }
                return webResponse.OK();
            };
            return base.Update(saveModel).Reload();
        }

        public override WebResponseContent Del(object[] keys, bool delList = true)
        {
            return base.Del(keys, delList).Reload();
        }
    }

}
